package ar.com.e2solver.solver.operator.mutation.impl;

import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.model.Coordinate;
import ar.com.e2solver.model.Puzzle;
import ar.com.e2solver.solver.Individual;
import ar.com.e2solver.solver.RandomConstants;
import ar.com.e2solver.solver.operator.mutation.MutationOperator;

/**
 * Intercambia dos columnas de un rompecabezas.
 * @author rodo
 *
 */
public final class ColumnExchangeMutationOperator implements MutationOperator {
	
	private static ColumnExchangeMutationOperator instance = new ColumnExchangeMutationOperator();
	
	private ColumnExchangeMutationOperator(){}

	public static ColumnExchangeMutationOperator getInstance() {
		return instance;
	}
	
	public Individual operate(Individual individualToMutate) throws BusinessException {
		Puzzle p = individualToMutate.getPuzzle().clone();
		
		if(p.getColumnNumbers() > 4){
			int col1 = RandomConstants.RANDOM.nextInt(p.getColumnNumbers() - 2) + 1;
			int col2 = RandomConstants.RANDOM.nextInt(p.getColumnNumbers() - 2) + 1;

			swapColumns(p, col1, col2);
		}
		
		return new Individual(p);
	}

	private void swapColumns(Puzzle p, int col1, int col2) throws BusinessException {
		Coordinate c1, c2;
		for (int i = 0; i < p.getRowsNumber(); i++) {
			c1 = new Coordinate(i, col1);
			c2 = new Coordinate(i, col2);
			p.swapPositions(c1, c2);
			
		}
	}
}
